package com.itheima.listener;

import com.alibaba.fastjson.JSON;
import com.itheima.domain.MoneyLog;
import com.itheima.service.MoneyLogService;
import com.itheima.service.RedPacketService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: cache
 * @description: java监听队列money
 * @author: zhanghz001
 * @create: 2021-04-27 15:27
 **/
@Component
public class ZhzMoneyListener {
    @Autowired
    private RedPacketService redPacketService;
    
    @Autowired
    private RabbitTemplate rabbitTemplate;
    
    @Autowired
    private MoneyLogService moneyLogService;
    
    /**
     * 监听队列
     */
    @RabbitListener
    public void moneyList(String message) throws Exception {
        try {
            System.out.println(message);
            Map<String, Object> map = JSON.parseObject(message, Map.class);
            String user = String.valueOf(map.get("user"));
            
            //    抢红包
            Double money = redPacketService.grab();
            if (money != null && money != 0) {
                
                //3)红包金额>0->抢红包成功，记录到数据库
                moneyLogService.add(new MoneyLog(money, user));
                //封装红包信息
                HashMap<String, Object> resultMap = new HashMap<>();
                resultMap.put("user", user);
                resultMap.put("money", money);
                resultMap.put("code", money > 0 ? 200 : 204);
                
                //发送MQ消息
                rabbitTemplate.convertAndSend("",
                        "redmessage.queue", JSON.toJSONString(resultMap));
                System.out.println("消息发送成功");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            
        }
    }
}
